package com.jyw.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyw.common.utils.DateUtils;
import com.jyw.system.domain.SysReceiveDepartConfig;
import com.jyw.system.domain.vo.SysReceiveDepartConfigVo;
import com.jyw.system.mapper.SysReceiveDepartConfigMapper;
import com.jyw.system.service.ISysReceiveDepartConfigService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author Created by ZhangCheng on 2023/08/17 (系统工单接单科室配置)
 */
@Service
public class SysReceiveDepartConfigServiceImpl extends ServiceImpl<SysReceiveDepartConfigMapper, SysReceiveDepartConfig> implements ISysReceiveDepartConfigService {

    @Override
    public List<SysReceiveDepartConfigVo> queryAllList() {
        return this.baseMapper.queryAllList();
    }

    @Override
    public int insert(SysReceiveDepartConfig sysReceiveDepartConfig) {
        sysReceiveDepartConfig.setCreateTime(DateUtils.getNowDate());
        return this.baseMapper.insert(sysReceiveDepartConfig);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertList(List<SysReceiveDepartConfig> configList) {
        List<SysReceiveDepartConfig> oldList=this.list();
        if (CollectionUtil.isNotEmpty(oldList)) {
            List<Long> ids = oldList.stream().map(SysReceiveDepartConfig::getId).collect(Collectors.toList());
            this.baseMapper.deleteBatchIds(ids);
        }
        if (CollectionUtil.isNotEmpty(configList)) {
            AtomicInteger index = new AtomicInteger(0);
            configList.forEach(config->{
                int newIndex = index.get() + 1;
                index.set(newIndex);
                config.setSort(newIndex);
                config.setCreateTime(DateUtils.getNowDate());
            });
           return this.saveBatch(configList);
        }
        return null;
    }

    @Override
    public int deleteBatchByIds(Long[] ids) {
        return this.baseMapper.deleteBatchByIds(ids);
    }
}
